<script setup lang="ts">
import {computed, onMounted, ref} from 'vue';
import {useRoute} from 'vue-router';
import {queryStudentPaper} from '../api/sysStudentAnswerSheet/sysStudentAnswerSheet';
import {ElMessage,ElMessageBox} from 'element-plus';
import CountdownTimer from '../uilts/countTime.vue';
import singleChoiceQuestion from '../uilts/question/singleChoiceQuestion.vue';
import multipleChoiceQuestion from '../uilts/question/multipleChoiceQuestion.vue';
import subjectiveQuestion from '../uilts/question/subjectiveQuestion.vue'
import judgeQuestion from "../uilts/question/judgeQuestion.vue";
import {updateStudentPaper} from '../api/sysStudentAnswerSheet/sysStudentAnswerSheet.ts';
import { useRouter } from 'vue-router';
import 'dayjs/locale/zh-cn';

import dayjs from "dayjs";

const router = useRouter();
// 倒计时组件
const iss = ref(false)
const countdownRef = ref(null)
const time = ref()
const second = ref(0)
const handleTimeUp = () => {
  iss.value = false
  ElMessage({
    type: 'success',
    message: '时间结束',
  })
  ElMessageBox.alert('确认提交', '时间结束', {
    confirmButtonText: 'OK',
  })  .then(() => {
    handleSubmit() // 提交表单
  })
}
const handleTick = (seconds) => {
  // 可以在这里处理每秒的回调
  second.value = seconds
  // console.log('剩余秒数:', seconds)
}

// --- 类型定义 ---
interface Option {
  id: string;
  content: string;
  isCorrect: boolean;
}

interface Question {
  id: string;
  type: 'single' | 'multiple' | 'judge';
  content: string;
  score: number;
  options: Option[];
  studentAnswer: string | string[] | null;
  correctAnswer: string | string[] | null;
}

interface ExamData {
  id: string;
  tesPaperName: string;
  subject: string;
  studentName: string;
  teacherName: string; // 统一为 string 类型
  createTime: string;
  testStartTime: string;
  endTime: string;
  timeLimit: number;
  timeTaken: string;
  state: number;
  content: Question[];
}

// --- 逻辑 ---
const route = useRoute();
const examId = route.query.id as string;
const s = route.query.s as string

// 使用 ref 管理整个数据对象，初始为 null
const examData = ref<ExamData | null>(null);
const loading = ref<boolean>(false);

// 计算属性：根据状态码返回可读的文本
const stateText = computed(() => {
  // 使用可选链操作符防止 examData 为 null 时报错
  switch (examData.value?.state) {
    case 1:
      return '未开始';
    case 2:
      return '进行中';
    case 3:
      return '已提交,等待教师批改';
    case 4:
      return '已批改';
    default:
      return '未知状态';
  }
});

// 获取试卷数据
const fetchExamData = async () => {
  if (!examId) {
    ElMessage.warning('无效的试卷ID');
    return;
  }
  try {
    loading.value = true;
    const res = await queryStudentPaper({id: examId});
    // 直接赋值，更简洁
    examData.value = res.data[0];
    console.log('获取试卷数据成功:', examData.value);
    getQuestionCategory(examData.value?.content);
    time.value = res.data[0].timeLimit
    iss.value = true // 倒计时开始
  } catch (error: any) {
    console.error('获取试卷数据失败:', error);
    ElMessage.error(error.message || '获取试卷数据失败');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchExamData()
});

// 题目分类、客观/主观
const singleOPtions = ref([]);
const multipleOPtions = ref([]);
const judgeOptions = ref([]);
const textOptions = ref([]);

// 题目分类方法
const getQuestionCategory = (question: any) => {
  question.forEach((item: any) => {
    if (item.type === 'single') {
      singleOPtions.value.push(item)
    } else if (item.type === 'multiple') {
      multipleOPtions.value.push(item)
    } else if (item.type === "judge"){
      judgeOptions.value.push(item)
    } else if (!question.type) {
      textOptions.value.push(item)
    }
  });
  console.log("单选:", singleOPtions.value);
  console.log("多选:", multipleOPtions.value);
  console.log("判断:", judgeOptions.value)
  console.log("主观:", textOptions.value)
}

// 单选回调
function singleOnData(row: any) {
  // 替换
  console.log("单选1:", singleOPtions.value);
  singleOPtions.value = singleOPtions.value.map((item: any) => {
    if (item.id === row.id) {
      return {
        ...row
      };
    }
    return item;
  });
  console.log("单选2:", singleOPtions.value);
}

// 判断题回调
function judgeOptionsOnData(row: any){
  // 替换
  console.log("判断1:", judgeOptions.value);
  judgeOptions.value = judgeOptions.value.map((item: any) => {
    if (item.id === row.id) {
      return {
        ...row
      };
    }
    return item;
  });
  console.log("判断2:", judgeOptions.value);
}

// 多选回调
function multipleOnData(row: any) {
  // 替换
  console.log("多选1:", multipleOPtions.value);
  multipleOPtions.value = multipleOPtions.value.map((item: any) => {
    if (item.id === row.id) {
      return {
        ...row
      };
    }
    return item;
  });
  console.log("多选2:", multipleOPtions.value);
}

// 主观回调
function testOnData(row: any) {
  // 替换
  textOptions.value = textOptions.value.map((item: any) => {
    if (item.id === row.id) {
      return {
        ...row
      };
    }
    return item;
  });
}

// 获取客观得分
const getObjectiveScore = () => {
  // 判断单选得分
  let singleScore = 0;
  // 多选得分
  let multipleScore = 0;
  // 判断得分
  let judgeScore = 0;
  // 单选
  singleOPtions.value.forEach((item: any) => {
    item.options.forEach((option: any) => {
      if (option.isCorrect ==  true){
        if (option.text == item.modelValue) {
          singleScore += item.score;

        }
      }
    });
  });
  // 多选
  multipleOPtions.value.forEach((item: any) => {
    // console.log("多选:", item)
    // 1. 创建正确答案的数组并排序
    const correctAnswersArray = item.options.filter(option => option.isCorrect).map(option => option.text).sort();
    // 2. 创建用户选择的答案的数组并排序
    const userAnswersArray = item.checkedValues.sort();
    // 3. 比较排序后的字符串
    if (JSON.stringify(correctAnswersArray) === JSON.stringify(userAnswersArray)) {
      // 全部正确，加分
      multipleScore += item.score;
    } else {
      console.log(`题目 ${item.id} 回答错误，不得分`);
    }
  })
  judgeOptions.value.forEach((item: any) => {
    console.log("判断:", item)
    let a = "";
    let b = "";
    if (item.correctAnswer){
      a = "true"
    }else{
      a = "false"
    }
    if (item.radio){
      b = "true"
    }else{
      b = "false"
    }
    if (a === b) {
      judgeScore += item.score;
    } else {
      console.log(`题目 ${item.id} 回答错误，不得分`);
    }

    // if (item.radio === item.correctAnswer) {
    //   judgeScore += item.score;
    // } else {
    //   console.log(`题目 ${item.id} 回答错误，不得分`);
    // }
    // if (item.radio === "true") {
    //   if (item.correctAnswer){
    //     judgeScore += item.score;
    //   }
    // }else if (item.radio === "false"){
    //   if (!item.correctAnswer){
    //     judgeScore += item.score;
    //   }
    // }
  });
  console.log("单选得分:", singleScore)
  console.log("多选得分:", multipleScore)
  console.log("判断得分:", judgeScore)
  // 返回总分
  return singleScore + multipleScore + judgeScore;
}

const newDataList = () => {
  const contentData = [];
  singleOPtions.value.forEach((item: any) => {
    contentData.push({
      ...item
    });
  });
  multipleOPtions.value.forEach((item: any) => {
    contentData.push({
      ...item
    });
  });
  judgeOptions.value.forEach((item: any) => {
    contentData.push({
      ...item
    });
  });
  textOptions.value.forEach((item: any) => {
    contentData.push({
      ...item
    });
  });
  // 当前时间计算
  const currentTimeString = dayjs().format('YYYY年MM月DD日 HH:mm:ss');

  return {
    ...examData.value,
    content: contentData,
    timeTaken: (examData.value.timeLimit * 60) - second.value,
    objectiveTestScores: getObjectiveScore(),
    endTime: currentTimeString // <--- 传递的是普通的字符串
  };
}

// 提交
const handleSubmit = () => {
  // 数据
  const content = newDataList();
  // 提交
  ElMessageBox.alert('确认提交', 'info', {
    confirmButtonText: '确认',
  }).then(()=>{
    updateStudentPaper(content).then(() => {
      iss.value = false
      ElMessageBox.alert("您的客观题得分为："+getObjectiveScore()+"分,最终得分请等待教师评分。","提交成功",{
        confirmButtonText: 'OK',
      }).then(()=>{
        router.push("/main/ViewGrades");
      }).catch(()=>{
        router.push("/main/ViewGrades");
      })
    }).catch((error: any) => {
      ElMessage.error(error.message || '提交失败');
    });

  }).catch(()=>{
    ElMessage.error('用户取消提交');
  })

}

const putSubmit = () => {
  router.back()
}

</script>

<template>
  <div v-if="!examId" class="error-message">
    无法查看，无有效ID
  </div>
  <!-- 当 examData 存在时才渲染容器 -->
  <div v-else-if="examData" class="exam-container">
    <!-- 倒计时组件 -->
    <CountdownTimer
        :total-time="time"
        @time-up="handleTimeUp"
        @tick="handleTick"
        ref="countdownRef"
        v-if="iss && s != 'vivw'"
    />
    <el-card v-loading="loading" shadow="never">
      <template #header>
        <div class="card-header">
          <span class="paper-title">{{ examData.tesPaperName || '未命名试卷' }}</span>
          <!--          <span class="paper-title">{{ examData.id || '未命名试卷id' }}</span>-->
          <el-tag :type="examData.state === 3 ? 'success' : 'warning'" effect="plain">
            {{ stateText }}
          </el-tag>
        </div>
      </template>

      <!-- 试卷基本信息 -->
      <el-descriptions :column="3" border>
        <el-descriptions-item label="试卷id">{{ examData.id }}</el-descriptions-item>
        <el-descriptions-item label="模板id">{{ examData.tesPaperId }}</el-descriptions-item>
        <el-descriptions-item label="科目">{{ examData.subject }}</el-descriptions-item>
        <el-descriptions-item label="学生">{{ examData.studentName }}</el-descriptions-item>
        <el-descriptions-item label="教师">{{ examData.teacherName }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ examData.createTime }}</el-descriptions-item>
        <el-descriptions-item label="考试开始时间">{{ examData.testStartTime || '未开始' }}</el-descriptions-item>
        <el-descriptions-item label="提交时间">{{ examData.endTime || '未提交' }}</el-descriptions-item>
        <el-descriptions-item label="考试时长">{{ examData.timeLimit }} 分钟</el-descriptions-item>
        <!--        <el-descriptions-item label="用时">{{ examData.timeTaken || '0' }}</el-descriptions-item>-->
        <el-descriptions-item label="总分">
          {{ examData.content.reduce((sum, q) => sum + q.score, 0) }} 分
        </el-descriptions-item>
      </el-descriptions>

      <el-divider content-position="left">单选题</el-divider>
      <!-- 题目列表占位 -->
      <div v-if="singleOPtions.length === 0" class="placeholder-text">暂无题目</div>
      <!-- 在这里循环渲染题目列表 -->
      <div v-for="data in singleOPtions" :key="data.id" class="options-list">
        <singleChoiceQuestion :question="data" @on-data="singleOnData"/>
      </div>

      <el-divider content-position="left">多选题</el-divider>
      <div v-if="multipleOPtions.length === 0" class="placeholder-text">暂无题目</div>
      <!-- 在这里循环渲染题目列表 -->
      <div v-for="data in multipleOPtions" :key="data.id" class="options-list">
        <multipleChoiceQuestion :question="data" @on-data="multipleOnData"/>
      </div>

      <el-divider content-position="left">判断题</el-divider>
      <div v-if="judgeOptions.length === 0" class="placeholder-text">暂无题目</div>
      <!-- 在这里循环渲染题目列表 -->
      <div v-for="data in judgeOptions" :key="data.id" class="options-list">
        <judgeQuestion :question="data" @on-data="judgeOptionsOnData"/>
      </div>

      <el-divider content-position="left">主观题</el-divider>
      <div v-if="textOptions.length === 0" class="placeholder-text">暂无题目</div>
      <!-- 在这里循环渲染题目列表 -->
      <div v-for="data in textOptions" :key="data.id" class="options-list">
        <subjectiveQuestion :question="data" @on-data="testOnData"/>
      </div>
    </el-card>
    <el-affix position="bottom" :offset="20">
      <el-button v-if="s != 'vivw'" icon="Check" type="primary" @click="handleSubmit">提交</el-button>
      <el-button v-if="s == 'vivw'" icon="Back" type="primary" @click="putSubmit">返回</el-button>
    </el-affix>
  </div>
  <!-- 加载中或数据为空时的占位 -->
  <div v-else class="exam-container">
    <el-card v-loading="true" shadow="never"></el-card>
  </div>
</template>

<style scoped lang="scss">
.error-message {
  padding: 20px;
  text-align: center;
  color: #f56c6c;
  font-size: 16px;
}

.exam-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.paper-title {
  font-size: 20px;
  font-weight: bold;
}

.question-item {
  margin-bottom: 20px;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-title {
  font-size: 16px;
  font-weight: 500;
}

.options-container {
  padding: 10px 0;
}

.option-item {
  display: flex;
  align-items: center;
  padding: 10px 15px;
  margin-bottom: 8px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.option-item:hover {
  background-color: #f5f7fa;
}

/* 正确答案样式 */
.option-item.is-correct {
  background-color: #f0f9ff;
  border-color: #79bbff;
}

/* 错误答案样式 */
.option-item.is-wrong {
  background-color: #fef0f0;
  border-color: #f89898;
}

.option-label {
  font-weight: bold;
  margin-right: 10px;
  color: #606266;
}

.option-content {
  flex-grow: 1;
}

.option-tags {
  margin-left: 15px;
}

/* 新增占位文本样式 */
.placeholder-text {
  text-align: center;
  color: #909399;
  padding: 20px;
}

.options-list {
  .el-radio {
    display: block;
    margin-bottom: 10px;
    margin-left: 20px; // 缩进选项
    &.correct-option {
      color: #67c23a; // 正确答案用绿色高亮
      font-weight: bold;
    }
  }
}
</style>
